package org.example.handler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.example.Dto.AdminDto;
import org.example.mapper.UserMapper;
import org.example.pojos.Admin;
import org.example.utils.JsonUtil;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.hutool.core.collection.CollUtil;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : zhangbo
 * @data : 2024/7/12
 * @description :
 */
@Service
@Slf4j
public class MqMsgHandler implements MessageHandler {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void handle(Message message, Channel channel) throws Exception {
        log.info("开始保存异步消费数据: message:{}, channel:{}", message, channel);
        List<Admin> msgDtoList = JsonUtil.getObjectMapper().readValue(message.getBody(), new TypeReference<List<Admin>>() {
        });
        if (CollUtil.isEmpty(msgDtoList)) {
            log.info("mq中无信息");
            return;
        }

        try {
            List<Admin> collect = msgDtoList.stream().map(dto -> {
                Admin admin = new Admin();
                admin.setUpdateTime(new Date());
                admin.setStatus("1");
                admin.setUpdateTime(new Date());
                return admin;
            }).collect(Collectors.toList());
            userMapper.saveBatch(collect);
        } catch (Exception e) {
            log.info("批量更新异常",e,channel.getChannelNumber());
        }
    }

    @Override
    public void updateStatus(Message message, Channel channel) throws IOException {
        log.info("开始保存异步消费数据: message:{}, channel:{}", message, channel);
        List<Admin> msgDtoList = JsonUtil.getObjectMapper().readValue(message.getBody(), new TypeReference<List<Admin>>() {
        });
        if (CollUtil.isEmpty(msgDtoList)) {
            log.info("mq中无信息");
            return;
        }
        try {
            List<Admin> subside = msgDtoList.stream().map(list -> {
                Admin admin = new Admin();
                admin.setExitTime(new Date());
                admin.setUpdateTime(new Date());
                admin.setUpdatePerson("subside");
                return admin;
            }).collect(Collectors.toList());
            userMapper.saveBatch(subside);
        } catch (Exception e) {
            log.info("批量更新异常",e,channel.getChannelNumber());
        }
    }
}
